# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         permission
# Description:
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2019-11-03
# -------------------------------------------------------------------------------
from rest_framework import status
from rest_framework.mixins import UpdateModelMixin, DestroyModelMixin
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet, GenericViewSet

from QAPlatform.mixins import CustomCreateModelMixin
from apps.BasicAuthService.filters import PermissionFilter
from apps.BasicAuthService.models import Permission
from apps.BasicAuthService.serializers import PermissionSerializer, PermissionListSerializer, \
    PermissionNameListSerializer

__all__ = ['PermissionNameListViewSet', 'PermissionListViewSet', 'PermissionViewSet']


class PermissionNameListViewSet(ReadOnlyModelViewSet):
    """
    权限名称列表
    """
    queryset = Permission.objects.filter(is_deleted=False).values('id', 'name', 'parent')
    serializer_class = PermissionNameListSerializer
    filter_class = PermissionFilter
    pagination_class = None


class PermissionListViewSet(ReadOnlyModelViewSet):
    queryset = Permission.objects.filter(is_deleted=False)
    serializer_class = PermissionListSerializer
    filter_class = PermissionFilter
    pagination_class = None


class PermissionViewSet(CustomCreateModelMixin, UpdateModelMixin, DestroyModelMixin, GenericViewSet):
    queryset = Permission.objects.filter(is_deleted=False)
    serializer_class = PermissionSerializer

    def destroy(self, request, *args, **kwargs):
        id = kwargs.get('pk')
        permission = Permission.objects.get(id=id)
        permission.user.clear()
        permission.role.clear()
        permission.is_deleted = True
        permission.save()
        return Response(status=status.HTTP_204_NO_CONTENT)
